package com.cyanite.playlv2;

import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2.widget.PhotoListAdapter;
import com.cyanite.playlv2api.types.Group;
import com.cyanite.playlv2api.types.Info;
import com.cyanite.playlv2api.types.Response;
import com.cyanite.playlv2api.types.Task;
import com.cyanite.playlv2api.types.TaskCategory;
import com.cyanite.playlv2api.util.ConstantsUtils;
import com.cyanite.playlv2api.util.ConstantsUtils.TaskCategoryConsts;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SharePhotoActivity extends Activity    {

    public static final String EXTRA_USER_ID = PlayLv2.PACKAGE_NAME
        + ".SharePhotoActivity.EXTRA_USER_ID";
    public static final String EXTRA_TASK_CATEGORY_PARCEL = PlayLv2.PACKAGE_NAME
        + ".SharePhotoActivity.EXTRA_TASK_CATEGORY_PARCEL";

    private StateHolder mStateHolder;
    private ProgressDialog mProgressDialog;
    private TextView mTaskDescription;
    private ListView mPhotoList;
    private PhotoListAdapter mListAdapter;
    private View mViewProgressBar;
    private LinearLayout mEmpty;
    private EditText mInfo;

	private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

	public void onCreate(Bundle savedInstanceState)    {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.share_photo_activity);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        mStateHolder = new StateHolder();
        if (getIntent().hasExtra(EXTRA_USER_ID)) {
            mStateHolder.setUserId(getIntent().getExtras().getString(EXTRA_USER_ID));
        }
        if (getIntent().hasExtra(EXTRA_TASK_CATEGORY_PARCEL))  {
            mStateHolder.setTaskCategory((TaskCategory)getIntent().getExtras().getParcelable(EXTRA_TASK_CATEGORY_PARCEL));
        }
        mStateHolder.setIsLoggedInUser(
                mStateHolder.getUserId() == null ||
                mStateHolder.getUserId().equals(((PlayLv2) getApplication()).getUserId()));

        mStateHolder.startTaskPhotoHistory(this);

        mViewProgressBar = findViewById(R.id.sharePhotoProgress);
        mViewProgressBar.setVisibility(View.VISIBLE);

        ensureUi();
	}

	private void ensureUi()  {

	    setTitle(getString(R.string.trip_share_activity_label));

	    mEmpty = (LinearLayout) findViewById(R.id.llEmptyPhoto);
        mPhotoList = (ListView)findViewById(R.id.lvPhotoList);
	    mTaskDescription = (TextView)findViewById(R.id.tvPhotoListDescription);

        switch ( mStateHolder.getTaskCategory().getType() )    {
            case TaskCategoryConsts.TASK_CATEGORY_TYPE_STARTPOINT:
                setTitle(R.string.taskcategory_activity_startpoint);
                mTaskDescription.setText(R.string.trip_share_start_point_note);
                break;
            case TaskCategoryConsts.TASK_CATEGORY_TYPE_ENDPOINT:
                setTitle(R.string.taskcategory_activity_endpoint);
                mTaskDescription.setText(R.string.trip_share_end_point_note);
                break;
            case TaskCategoryConsts.TASK_CATEGORY_TYPE_TRIP_NOTE:
                setTitle(R.string.taskcategory_activity_note);
                mTaskDescription.setText(R.string.trip_share_trip_note);
                break;
            case TaskCategoryConsts.TASK_CATEGORY_TYPE_MOOD:
                setTitle(R.string.taskcategory_activity_mood);
                mTaskDescription.setText(R.string.trip_share_sport_mood);
                break;
            case TaskCategoryConsts.TASK_CATEGORY_TYPE_ANOTHER:
                setTitle(R.string.taskcategory_activity_other);
                mTaskDescription.setText(R.string.trip_share_another);
                break;
            case TaskCategoryConsts.TASK_CATEGORY_TYPE_SPECIAL:
                setTitle(R.string.taskcategory_activity_special);
                mTaskDescription.setText(R.string.trip_share_special);
                break;
            default:
                break;
        }

        mInfo = (EditText)findViewById(R.id.etPhotoListShout);
        
      //  mInfo.setFocusable(false);
      //  mInfo.setFocusableInTouchMode(true);
        ImageView camera = (ImageView)findViewById(R.id.ivPhotocamera);
        camera.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
               Intent intent = new Intent(SharePhotoActivity.this, ShareShoutWithPhotoActivity.class);
               intent.putExtra(ShareShoutWithPhotoActivity.EXTRA_TASK_CATEGORY_PARCEL, mStateHolder.getTaskCategory());
               startActivity(intent);
            }
        });

        Button btnShare = (Button)findViewById(R.id.btnPhotoListCreate);
        btnShare.setOnClickListener(new Button.OnClickListener()  {
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mInfo.getText().toString())) {
                    Info info = new Info();
                    info.setInfo1(mInfo.getText().toString());
                    mStateHolder.startTaskSharePhoto(SharePhotoActivity.this, info);
                } else {
                    Toast.makeText(SharePhotoActivity.this,
                            getResources().getString(R.string.share_info_content_null),
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        if ( mStateHolder.getIsLoggedInUser() )    {
            camera.setVisibility(View.VISIBLE);
            mInfo.setVisibility(View.VISIBLE);
            btnShare.setVisibility(View.VISIBLE);
        }   else   {
            camera.setVisibility(View.GONE);
            mInfo.setVisibility(View.GONE);
            btnShare.setVisibility(View.GONE);
        }
	}

	@Override
    public void onPause() {
        super.onPause();
    }

	@Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLoggedOutReceiver);
    }

    private void onHistoryTaskComplete(Group<Task> tasks, Exception ex) {
        mViewProgressBar.setVisibility(View.GONE);
        if ( tasks != null && tasks.size() > 0 ) {
            mEmpty.setVisibility(View.GONE);
            mListAdapter = new PhotoListAdapter(this,
                    ((PlayLv2) getApplication()).getRemoteResourceManager(), tasks);
            mPhotoList.setAdapter(mListAdapter);
        }   else {
            mEmpty.setVisibility(View.VISIBLE);
        }

    }

    private static class ShareHistoryTask extends AsyncTask<Void, Void, Group<Task>> {

        private SharePhotoActivity mActivity;
        private Exception mReason;
        private String mTaskCategoryId;
        private String mViewUserId;

        public ShareHistoryTask(SharePhotoActivity activity, String viewUserId, String taskcatId) {
            mActivity = activity;
            mTaskCategoryId = taskcatId;
            mViewUserId = viewUserId;
        }

        @Override
        protected Group<Task> doInBackground(Void... params) {
            try {
                return ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().tasks(mViewUserId, mTaskCategoryId);
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Group<Task> tasks) {
            if (mActivity != null) {
                mActivity.onHistoryTaskComplete(tasks, mReason);
            }
        }
    }

    private void onSharePhotoTaskComplete(Response response, Exception ex) {
        dismissProgressDialog();
        if (response != null && response.getValue().equals("0")) {
            Toast.makeText(SharePhotoActivity.this,
                    getResources().getString(R.string.share_info_ok),
                    Toast.LENGTH_LONG).show();
            mStateHolder.startTaskPhotoHistory(SharePhotoActivity.this);
        } else {
            NotificationsUtil.ToastReasonForFailure(this, ex);
        }
    }

    private static class SharePhotoTask extends AsyncTask<Void, Void, Response> {

        private SharePhotoActivity mActivity;
        private Exception mReason;
        private Task mTask;

        public SharePhotoTask(SharePhotoActivity activity, Task task) {
            mActivity = activity;
            mTask = task;
        }

        @Override
        protected void onPreExecute() {
            mActivity.showProgressDialog();
        }

        @Override
        protected Response doInBackground(Void... params) {
            String validateGps = "1";
            Location loc = ((PlayLv2)mActivity.getApplication()).getLastKnownLocation();
            if (loc == null) {
                try {
                    Thread.sleep(ConstantsUtils.SLEEP_TIME_IF_NO_LOCATION);
                    } catch (InterruptedException ex) {}
                loc = ((PlayLv2)mActivity.getApplication()).getLastKnownLocation();
            }
            if (loc != null)    {
                mTask.setLatitude(String.valueOf(loc.getLatitude()));
                mTask.setLongitude(String.valueOf(loc.getLongitude()));
            }   else {
                validateGps = "2";
            }
            try {
                Response response = null;
                response = ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().share(mTask, validateGps);
                if (response == null) response = new Response();
                return response;
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.onSharePhotoTaskComplete(response, mReason);
            }
        }

        @Override
        protected void onCancelled() {
            mActivity.dismissProgressDialog();
        }
    }

    private static class StateHolder {

        private String mUserId;
        private boolean mIsLoggedInUser;
        private SharePhotoTask mTaskSharePhoto;
        private ShareHistoryTask mTaskShareHistory;
        private TaskCategory mTaskCategory;
        private Group<Task> mTasks;

        public StateHolder() {
            mIsLoggedInUser = false;
        }

        Group<Task> getTasks(){
            return mTasks;
        }

        void setTasks(Group<Task> tasks){
            mTasks = tasks;
        }

        public boolean getIsLoggedInUser() {
            return mIsLoggedInUser;
        }

        public String getUserId() {
            return mUserId;
        }

        public void setUserId(String userId) {
            mUserId = userId;
        }

        public void setIsLoggedInUser(boolean isLoggedInUser) {
            mIsLoggedInUser = isLoggedInUser;
        }

        public TaskCategory getTaskCategory() {
            return mTaskCategory;
        }

        public void setTaskCategory(TaskCategory taskcat) {
            mTaskCategory = taskcat;
        }

        public void startTaskSharePhoto(SharePhotoActivity activity, Info info) {
            Task task = new Task();
            task.setInfo(info);
            task.setTaskCategoryId(mTaskCategory.getId());
            mTaskSharePhoto = new SharePhotoTask(activity, task);
            mTaskSharePhoto.execute();
        }

        public void startTaskPhotoHistory(SharePhotoActivity activity) {
            mTaskShareHistory = new ShareHistoryTask(activity, mUserId, mTaskCategory.getId());
            mTaskShareHistory.execute();
        }

        public void cancelTasks() {
            if (mTaskSharePhoto != null) {
                mTaskSharePhoto.cancel(true);
            }
            if (mTaskShareHistory != null) {
                mTaskShareHistory.cancel(true);
            }
        }
    }

    private ProgressDialog showProgressDialog() {
        if (mProgressDialog == null) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.share_info_progress_note));
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            mProgressDialog = dialog;
        }
        mProgressDialog.show();
        return mProgressDialog;
    }

    private void dismissProgressDialog() {
        try {
            mProgressDialog.dismiss();
        } catch (IllegalArgumentException e) {
            // We don't mind. android cleared it for us.
        }
    }

}
